package formula.business.aspects;

import org.aspectj.lang.JoinPoint;

/**
 * enables to track Connection access : getConnection() and cnx.close()
 * @author Gauthier Peel
 *
 */
public aspect MyTraceConnectionAspect {

	private int callDepth;

	pointcut tracedDbcpGet()   : execution( * org.apache.commons.dbcp.BasicDataSource.getConnection() ) ;
	pointcut tracedDbcpClose() : execution( * java.sql.Connection.close() ) ;

	pointcut traced(Object myTarget) : (tracedDbcpClose() || tracedDbcpGet()) &&  target(myTarget);

//	before(Object myTarget) : traced(myTarget) {
//		print(": @" + Integer.toHexString(myTarget.hashCode()) + " ", thisJoinPoint);
//		callDepth++;
//	}
//
//	after(Object myTarget) : traced(myTarget) {
//		callDepth--;
//	}

	private void print(String prefix, JoinPoint _jointPoint) {
		for (int i = 0; i < callDepth; i++) {
			System.out.print(" ");
		}
		String msg = prefix + _jointPoint.getSignature().toShortString();
		String s2 = createParameterMessage(_jointPoint);
		if (s2 != null) {
			msg = msg + s2;
		}
		System.out.println(msg);
	}

	private String createParameterMessage(JoinPoint joinPoint) {
		Object[] arguments = joinPoint.getArgs();
		if (arguments.length == 0) {
			return null;
		}
		StringBuffer paramBuffer = new StringBuffer("\n\t[This: ");
		paramBuffer.append(joinPoint.getThis());
		paramBuffer.append("]\n\t[Args: (");
		for (int length = arguments.length, i = 0; i < length; ++i) {
			Object argument = arguments[i];
			paramBuffer.append(argument);
			if (i != length - 1) {
				paramBuffer.append(',');
			}
		}
		paramBuffer.append(")]");
		return paramBuffer.toString();
	}
}

